package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-09-07
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    // 会员登录
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //1.非空判断
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        if (phone==null||code==null){
            throw new YyghException(20001,"数据为空");
        }
        //2.手机验证码校验
        String phoneCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(phoneCode)){
            throw new YyghException(20001,"验证码失败");
        }
        //3.判断手机好是否第一次登录
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",phone);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        if (userInfo==null){
        //4.根据手机号去数据库查 查不到 证明是第一次登录 需要注册
            userInfo=new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            userInfo.setAuthStatus(0);
            baseMapper.insert(userInfo);
        }
        //5.判断用户是否锁定
        if (userInfo.getStatus()==0){
            throw new YyghException(20001,"用户被锁定");
        }
        //6.登录后返回数据
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){
            name=userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)){
            name=userInfo.getPhone();
        }

        map.put("name",name);

        //生成token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        return map;
    }

    @Override
    public UserInfo findUserByOpenid(String openid) {
        QueryWrapper wrapper =new QueryWrapper();
        wrapper.eq("openid",openid);

        return   baseMapper.selectOne(wrapper);
    }
}
